﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace RbacPermissionSystem.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UploadImageController : ControllerBase
    {
        private readonly IWebHostEnvironment web;
        private readonly IConfiguration configuration;

        public UploadImageController(IWebHostEnvironment web, IConfiguration configuration)
        {
            this.web = web;
            this.configuration = configuration;
        }

        /// <summary>
        /// 上传头像 <input type="file" value="123" name='file' id='age'></input> web根  内容根
        /// WebRootPath  ContentRootPath
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadAvatarAsync(IFormFile file)
        {         
            if(file.Length / 1024  > 5000) 
            {
                throw new Exception("文件大小超出范围");
            }

            string fileExt = Path.GetExtension(file.FileName);

            string[] fileExts = configuration["FileExts"].Split(',');

            if(fileExts.Any(m => m == fileExt))
            {
                throw new Exception("后缀不对");
            }


            //目录路径
            string DirPath = $"/images/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}/";

            if(!Directory.Exists($"{web.WebRootPath}{DirPath}"))
            {
                Directory.CreateDirectory($"{web.WebRootPath}{DirPath}");
            }

            //文件名           

            Random random = new Random();
            int randomNum = random.Next(1000, 9999);


            string newFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-{randomNum}{fileExt}";

            using (FileStream fileStream = new FileStream($"{web.WebRootPath}/{DirPath}{newFileName}", FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }

            return Ok(new
            {
                fileName = $"{DirPath}{newFileName}"
            });
        }
    }
}
